{% extends 'layout/manage.html' %}
{% load static %}
{% block css %}
    <style>
        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default > .panel-heading a {
            text-decoration: none;
        }

        .panel-default > .panel-heading span {
            padding: 0 5px;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .uploadProgress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }

        .uploadProgress .progress-error {
            color: red;
        }
    </style>
{% endblock %}

{% block content %}
    <!-- 布局 -->
    <div class="bs-example" data-example-id="panel-without-body-with-table">
        <div class="panel panel-default" style="margin: 20px">
            <!-- Default panel contents -->
            <div class="panel-heading">
                <div>
                    <a href="{% url 'file' project_id=request.tracer.project.id %}">
                        <i class="fa fa-home" aria-hidden="true"></i>
                        <span>文件库</span>
                    </a>
                    {% for record in breadcrumb_list %}
                        <a href="{% url 'file' project_id=request.tracer.project.id %}?folder={{ record.id }}">
                            <i class="fa fa-caret-right" aria-hidden="true"></i>
                            <span>{{ record.name }}</span>
                        </a>
                    {% endfor %}
                </div>
                <div class="function">
                    {# 上传文件按钮 #}
                    <div class="btn btn-primary btn-xs upload" style="position: relative;">
                        <div><i class="fa fa-upload" aria-hidden="true"></i>上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile">
                    </div>
                    {# data-toggle="modal" 允许弹出框 data-target="#addModal" 绑定模态框id data-whatever="新建文件夹" 自定义对话框名称 #}
                    <a class="btn btn-success btn-xs" data-toggle="modal" data-target="#addModal" data-whatever="新建文件夹">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i> 新建文件夹
                    </a>
                </div>
            </div>

            <!-- Table -->
            <table class="table">
                <thead>
                <tr>
                    <th>名称</th>
                    <th>文件大小</th>
                    <th>更新者</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="rowList">
                {% for file_object in file_object_list %}
                    <tr>
                        <td>
                            {% if file_object.file_type == 1 %}
                                <i class="fa fa-file" aria-hidden="true"></i> {{ file_object.name }}
                            {% else %}
                                <a href="{% url 'file' project_id=request.tracer.project.id %}?folder={{ file_object.id }}">
                                    <i class="fa fa-folder" aria-hidden="true"></i> {{ file_object.name }}
                                </a>
                            {% endif %}

                        </td>
                        <td>
                            {% if file_object.file_type == 1 %}
                                {{ file_object.file_size }}
                            {% else %}
                                -
                            {% endif %}
                        </td>
                        <td>{{ file_object.update_user.username }}</td>
                        <td>{{ file_object.update_datetime }}</td>
                        <td>
                            {% if file_object.file_type == 2 %}
                                {# data-toggle="modal" 允许弹出框 data-target="#addModal" 绑定模态框id data-whatever="新建文件夹" 自定义对话框名称 #}
                                <a class="btn btn-default btn-xs" data-toggle="modal" data-target="#addModal"
                                   data-whatever="编辑文件夹"
                                   data-name="{{ file_object.name }}" data-fid="{{ file_object.id }}">
                                    <i class="fa fa-pencil-square-o" aria-hidden="true"></i> 编辑
                                </a>
                            {% else %}
                                <a class="btn btn-default btn-xs"
                                   href="{% url 'file_download' project_id=request.tracer.project.id file_id=file_object.id %}">
                                    <i class="fa fa-cloud-download" aria-hidden="true"></i> 下载
                                </a>
                            {% endif %}
                            <a class="btn btn-default btn-xs" data-toggle="modal" data-target="#delModal"
                               data-fid="{{ file_object.id }}">
                                <i class="fa fa-trash" aria-hidden="true"></i> 删除
                            </a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    <!-- 新建/编辑 文件夹对话框 -->
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                </div>
                <div class="modal-body">
                    {# 表单内容 #}
                    <form id="fileform">
                        {% csrf_token %}
                        <input class="hide" type="text" name="fid" id="fid" value="">
                        {% for field in form %}
                            <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field }}
                                <span class="error-msg">{{ field.error.0 }}</span>
                            </div>
                        {% endfor %}
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                    <button id="btnFormSubmit" type="button" class="btn btn-primary">确 定</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 删除对话框 -->
    <div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <!-- 警告框 -->
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4>删除文件/夹！</h4>
                <p style="padding-top: 20px;padding-bottom: 20px">文件/夹中包含的所有文件都会被删除？</p>
                <p style="text-align: right">
                    <button type="button" class="btn btn-default btn-sm" aria-label="close" data-dismiss="modal">取 消
                    </button>
                    <button id="btnDelete" type="button" class="btn btn-danger btn-sm">删 除</button>
                </p>
            </div>
        </div>
    </div>
    <!-- 上传文件进度条 -->
    <div id="uploadProgress" class="uploadProgress hide">
        {# 面板 #}
        <div class="panel panel-primary">
            <div class="panel-heading"><i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传进度</div>
            <table class="table">
                <tbody id="progressList">
                {# 调用模板 #}
                </tbody>
            </table>
        </div>
    </div>
    <!-- 上传文件进度,调用模板 -->
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0"
                             aria-valuemax="100" style="width: 0">
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>
    <!-- 上传文件成功,调用模板，显示上传的表格 -->
    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i> <span class="name"></span>
                </td>
                <td class="file-size"></td>
                <td class="update_user__username"></td>
                <td class="update_datetime"></td>
                <td>
                    <a class="btn btn-default btn-xs download">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i> 下载
                    </a>
                    <a class="btn btn-default btn-xs delete"
                       data-toggle="modal"
                       data-target="#delModal">
                        <i class="fa fa-trash" aria-hidden="true"></i> 删除
                    </a>
                </td>
            </tr>
        </table>

    </div>

{% endblock %}

{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        var FOLDER_URL = "{% url 'file' project_id=request.tracer.project.id %}";
        var FILE_DELETE_URL = "{% url 'file_delete' project_id=request.tracer.project.id %}";
        var COS_CREDENTIAL_URL = "{% url 'cos_credential' project_id=request.tracer.project.id %}";
        var FILE_POST_URL = "{% url 'file_post' project_id=request.tracer.project.id %}";
        var CURRENT_FOLDER_ID = "{{ folder_object.id }}";


        $(function () {
            initModal();
            bindModelSubmit();
            bindBtnDelete();
            bindUploadFile();
        })

        //上传文件按钮
        function bindUploadFile() {
            //获取临时凭证，5分钟
            $('#uploadFile').change(function () {
                //清空上次内容
                $('#progressList').empty();

                //获取本次上传的所有文件名和大小，构造成字典
                var checkFileList = [];
                var fileList = $(this)[0].files;

                $.each(fileList, function (index, fileObject) {
                    var fileName = fileObject.name;
                    var fileSize = fileObject.size;

                    checkFileList.push({'name': fileName, 'size': fileSize});
                });

                //把数据返回给后台，判断容量大小，通过则返回临时凭证
                var cos_credential = new COS({
                    getAuthorization: function (options, callback) {
                        $.post(COS_CREDENTIAL_URL, JSON.stringify(checkFileList), function (res) {
                            if (res.status) {
                                var credentials = res.data && res.data.credentials;
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    SecurityToken: credentials.sessionToken,
                                    // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                                    StartTime: res.data.startTime, // 时间戳，单位秒，如：1580000000
                                    ExpiredTime: res.data.expiredTime, // 时间戳，单位秒，如：1580000900
                                });
                                //校验成功后 展示进度框
                                $('.uploadProgress').removeClass('hide');
                            } else {
                                alert(res.error);
                            }
                        });
                    }
                });

                //上传文件(异步)
                $.each(fileList, function (index, fileObject) {
                    // 获取文件名,大小
                    var fileName = fileObject.name;
                    var fileSize = fileObject.size;
                    var key = (new Date()).getTime() + "_" + fileName;
                    // 调用进度条
                    var tr = $('#progressTemplate').find('tr').clone();
                    tr.find('.name').text(fileName);
                    $('#progressList').append(tr);
                    //上传文件至腾讯存储cos
                    cos_credential.putObject({
                        Bucket: '{{ request.tracer.project.bucket }}', /* 必须 */
                        Region: '{{ request.tracer.project.region }}',     /* 存储桶所在地域，必须字段 */
                        Key: key,              /* 必须 */
                        Body: fileObject, // 上传文件对象
                        onProgress: function (progressData) {
                            {#console.log("文件上传进度--->", fileName, progressData);#}
                            var percent = progressData.percent * 100 + '%';
                            {#console.log(percent)#}
                            tr.find('.progress-bar').text(percent);
                            tr.find('.progress-bar').css('width', percent);
                        }
                    }, function (err, data) {
                        {#console.log(err || data);#}
                        //上传成功之后将文件信息写入数据库
                        if (data && data.statusCode == 200) {
                            $.post(FILE_POST_URL, {
                                name: fileName,
                                key: key,
                                file_size: fileSize,
                                parent: CURRENT_FOLDER_ID,
                                etag: data.ETag,
                                file_path: data.Location,
                            }, function (res) {
                                //数据库加入成功
                                var newTr = $('#rowTpl').find('tr').clone();
                                newTr.find('.name').text(res.data.name);
                                newTr.find('.file-size').text(res.data.file_size);
                                newTr.find('.update_user__username').text(res.data.username);
                                newTr.find('.update_datetime').text(res.data.datetime);
                                newTr.find('.delete').attr('data-fid', res.data.id);
                                newTr.find('.download').attr('href', res.data.download_url);
                                $('#rowList').append(newTr);

                                //隐藏进度条
                                setTimeout(function () {
                                    tr.remove();
                                    $('#uploadProgress').addClass('hide');
                                    {#location.href = location.href;#}
                                }, 3000);

                            })
                        } else {
                            tr.find('.progress-error').text('上传失败');
                        }
                    });
                });
            })
        }

        //删除按钮事件
        function bindBtnDelete() {
            $('#btnDelete').click(function () {
                $.ajax({
                    url: FILE_DELETE_URL,
                    type: "GET",
                    data: {"fid": $(this).attr('fid')},
                    success: function (res) {
                        if (res.status) {
                            location.href = location.href;
                        }
                    }
                })
            })
        }

        //初始化两个模态框
        function initModal() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var recipient = button.data('whatever'); // Extract info from data-* attributes
                var name = button.data('name'); // Extract info from data-* attributes
                var fid = button.data('fid'); // Extract info from data-* attributes
                var modal = $(this);
                modal.find('.modal-title').text(recipient);
                if (fid) {
                    //编辑
                    modal.find('#id_name').val(name);
                    modal.find('#fid').val(fid);
                } else {
                    //新建
                    //清空上次输入的错误提示
                    modal.find('.error-msg').empty();
                    //清空上次输入的表单值
                    $('#fileform')[0].reset();
                }
            });
            $('#delModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var fid = button.data('fid'); // Extract info from data-* attributes
                $('#btnDelete').attr("fid", fid);

            });
        }

        //新建编辑文件夹确定 提交
        function bindModelSubmit() {
            $('#btnFormSubmit').click(function () {
                $.ajax({
                    url: location.href,
                    type: "POST",
                    data: $("#fileform").serialize(),
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            location.href = location.href;
                            {#console.log(res);#}
                        } else {
                            //如果出现错误，则在错误的表格底下显示错误信息
                            $.each(res.error, function (key, value) {
                                $("#id_" + key).next().text(value[0])
                            });
                        }
                    }

                })
            })
        }
    </script>
{% endblock %}
